using Luban;
using Config;
using TEngine;
using UnityEngine;
using SimpleJSON;
using System.IO;

/// <summary>
/// 配置加载器。
/// </summary>
public class ConfigSystem
{
    private static ConfigSystem _instance;

    public static ConfigSystem Instance => _instance ??= new ConfigSystem();

    private bool _init = false;

    private Tables _tables;

    public Tables Tables
    {
        get
        {
            if (!_init)
            {
                Load();
            }

            return _tables;
        }
    }
    
    private IResourceModule _resourceModule;

    /// <summary>
    /// 加载配置。
    /// </summary>
    public void Load()
    {
        /*_tables = new Tables(LoadByteBuf);
        _init = true;*/
        var tablesCtor = typeof(Tables).GetConstructors()[0];
        var loaderReturnType = tablesCtor.GetParameters()[0].ParameterType.GetGenericArguments()[1];

        System.Delegate loader = loaderReturnType == typeof(ByteBuf)
            ? new System.Func<string, ByteBuf>(LoadByteBuf)
            : (System.Delegate)new System.Func<string, JSONNode>(LoadJson);
        _tables = (Tables)tablesCtor.Invoke(new object[] { loader });
        _init = true;
    }

    /// <summary>
    /// 加载二进制配置。
    /// </summary>
    /// <param name="file">FileName</param>
    /// <returns>ByteBuf</returns>
    private ByteBuf LoadByteBuf(string file)
    {
        if (_resourceModule == null)
        {
            _resourceModule = ModuleSystem.GetModule<IResourceModule>();
        }
        TextAsset textAsset = _resourceModule.LoadAsset<TextAsset>(file);
        byte[] bytes = textAsset.bytes;
        return new ByteBuf(bytes);
    }
    /// <summary>
    /// 加载Json配置。
    /// </summary>
    /// <param name="file">FileName</param>
    /// <returns>JSONNode</returns>
    private JSONNode LoadJson(string file)
    {
       
#if UNITY_EDITOR
        var ret = File.ReadAllText($"{Application.dataPath}/../GenerateDatas/json/{file}.json",
            System.Text.Encoding.UTF8);
#else
        var textAssets =
 GameModule.Resource.LoadAsset<TextAsset>($"{SettingsUtils.FrameworkGlobalSettings.ConfigFolderName}{file}.json");
        var ret = textAssets.text;
#endif
        return JSON.Parse(ret);
    }
}